package com.drop.dao.impl;

import com.drop.dao.GoodsDao;
import com.drop.entity.Goods;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by 陈东一 on 2017/9/24 18:50
 */
@Repository
public class GoodsDaoImpl implements GoodsDao {

	private Log log = LogFactory.getLog(this.getClass());

	private SessionFactory sessionFactory;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession(){
		return sessionFactory.getCurrentSession();
	}


	@Override
	public List<Goods> getGoodsByIds(List<String> ids) throws Exception {
		StringBuilder hql = new StringBuilder(" from com.drop.entity.Goods c where c.goodsId in (");
		for (int i=0;i<ids.size();i++){
			if(i==0){
				hql.append(ids.get(i));
			}else{
				hql.append(" , ");
				hql.append(ids.get(i));
			}
		}
		hql.append(")");
		hql.append("  ORDER BY   INSTR(',");
		for (int i=0;i<ids.size();i++){
			hql.append(ids.get(i)+",");
		}
		hql.append("',CONCAT(',',c.goodsId,','))");
		log.info(hql.toString());
		return getSession().createQuery(hql.toString()).list();
	}

	@Override
	public List<Goods> getGoodsByTerm(String str) {
		String hql="from Goods gd where gd.goodsContent like '%" + str + "%'";
		return getSession().createQuery(hql).list();
	}

	@Override
	public Boolean insertGoods(String goodstype, String goodsName, String goodsContent, String price, String stock, String goodsImg, int shopId, int i) {
		String sql = "INSERT INTO `goods` (goodsName, goodsImg, goodsContent, shopId, districtId, price, goodsTypeId, stock, salesNum)  " +
				"VALUES ('"+goodsName+"','"+goodsImg+"','"+goodsContent+"','"+shopId+"','"+1+"','"+price+"','"+goodstype+"','"+stock+"','"+0+"') ; ";
		log.info(sql);
		return getSession().createSQLQuery(sql).executeUpdate() > 0 ;
	}
}
